var models = require('../models');
var Topic = models.Topic;
var User = models.User;
var Reply = models.Reply;
var userServ = require('./user');
var EventProxy = require('eventproxy');
var tools = require('../common/tools');
var _ = require('lodash');
var config = require('../config');

//获取完整主题信息（包括作者，不包括回复列表）
exports.getFullTopicById = function (id, callback) {
	var ep = new EventProxy();
	ep.fail(callback);

	Topic.findById(id, ep.done(function (topic) {
		if (!topic) return callback(null, '主题不存在！');

		//创建日期格式化
		topic.createAtformatted = tools.formatDate(topic.createAt);

		ep.all('author', function (user) {
			topic.author = user;
			callback(null, '', topic);
		});
		
		//获取主题作者
		userServ.getFullUserById(topic.authorId, ep.done(function (msg, user) {
			if (msg) return callback(null, msg);
			else ep.emit('author', user);
		}));
	}));
};

//查询主题列表（可分页）
exports.queryList = function (query, options, callback) {
	var ep = new EventProxy();
	ep.fail(callback);
	Topic.find(query, null, options, ep.done(function (topics) {
		ep.after('topic_ready', topics.length, function () {
			_.compact(topics);
			callback(null, topics);
		});
		topics.forEach(function (topic, i) {
			//创建日期格式化
			topic.createAtformatted = tools.formatDate(topic.createAt);

			var p = new EventProxy();
			p.fail(callback);
			p.all('author', 'reply_count', function (user, replyCount) {
				if (!user)
					topics[i] = null;
				else
					topic.authorName = user.loginName;
				topic.replyCount = replyCount;
				ep.emit('topic_ready');
			});
			
			//获取主题作者、回复数量
			User.findById(topic.authorId, p.done('author'));
			Reply.count({ topicId: topic._id }, p.done('reply_count'));
		});
	}));
};

//查询主题列表数量（可分页）
exports.queryPage = function (query, callback) {
	Topic.count(query, function (err, count) {
		if (err) return callback(err);
		var pageTotal = Math.ceil(count / config.topicPageLimit);
		callback(null, pageTotal);
	})
};